const fileService = require("../service/file.service");
const userService = require("../service/user.service");
const { APP_HOST, APP_PORT } = require("../config/config");

class FileController {
	async saveAvatarInfo(ctx, next) {
		// 获取图像信息和用户id
		const { filename, mimetype, size } = ctx.request.file;
		const user_id = ctx.user.id;
		// 将图像信息数据保存到数据库
		await fileService.saveAvatarInfo(filename, mimetype, size, user_id);

		// 将头像地址保存到 users 表
		const avatarUrl = `${APP_HOST}:${APP_PORT}/users/avatar/${user_id}`;
		await userService.updateAvatarUrlById(user_id, avatarUrl);

		// 返回数据
		ctx.body = {
			code: 200,
			message: "头像上传成功",
			url: avatarUrl
		};
	}

	async savePictureInfo(ctx, next) {
		// 获取图像信息、内容id、用户id
		const files = ctx.request.files;
		const user_id = ctx.user.id;
		const moment_id = ctx.request.body.momentId;

		// 将图像信息保存到数据库
		for (let file of files) {
			const { filename, mimetype, size } = file;
			await fileService.savePictureInfo(
				filename,
				mimetype,
				size,
				moment_id,
				user_id
			);
		}

		// 返回数据
		ctx.body = {
			code: 200,
			message: "上传配图成功"
		};
	}
}

module.exports = new FileController();
